import {
  Component,
  OnInit,
  Input,
  Output,
  EventEmitter,
  ChangeDetectorRef,
} from "@angular/core";
import { PL00SymbolTable } from "src/interpreter/PL00SymbolTable";
import {
  FunctionSymbol,
  ProcedureSymbol,
  FunctionArgument,
} from "src/interpreter/PL00Symbols";

@Component({
  selector: "app-pl00-console",
  templateUrl: "./pl00-console.component.html",
  styleUrls: ["./pl00-console.component.css"],
})
export class Pl00ConsoleComponent implements OnInit {
  constructor(private cdf: ChangeDetectorRef) {}
  // 访问器
  _visitor: any;
  // 自动输入
  inputText: string;
  // 修改自动输入的事件
  @Output() changeText: EventEmitter<string> = new EventEmitter<string>();
  // 将访问器中的符号表格式化
  get symbolList() {
    let symbols: { name: string; value: string }[] = [];
    if (this.visitor?.symbolTable?.scopes?.length) {
      // 最后一个作用域（其实大概应该设定成第一个作用域）
      for (const symbolName of this.visitor.symbolTable.scopes[
        this.visitor.symbolTable.scopes.length - 1
      ]) {
        const symbol = this.visitor.symbolTable.get(symbolName);
        // 排除函数和过程符号
        if (![FunctionSymbol, ProcedureSymbol].includes(symbol.type)) {
          const functionSymbol = this.visitor.symbolTable.getFunction("toStr", [
            symbol,
          ]);
          if (functionSymbol === null) {
            continue;
          }
          this.visitor.loopRestriction = 500;
          // 调用toStr显示
          const value = this.visitor.callFunction("toStr", [symbol])?.value;
          symbols.push({ name: symbolName, value: value });
        }
      }
    }
    return symbols;
  }
  set visitor(value) {
    this._visitor = value;
    // 主动检测更改
    this.cdf.detectChanges();
    // console.log(this._visitor?.symbolTable)
  }
  get visitor() {
    return this._visitor;
  }
  @Input() set output(value: string) {
    this._output = value;
    // 这个好像并没有起作用（小声）
    this.loading = false;
    // 对于MathJax的特殊渲染
    if (value.includes("$")) {
      (window as any).MathJax.typesetPromise().then(() => {
        // console.log("???");
        (window as any).MathJax.typesetPromise();
      });
    }
    // this.mathService.render()
  }
  get output() {
    return this._output;
  }
  @Output() runRequest = new EventEmitter();

  _output: string;
  loading: boolean = false;

  ngOnInit(): void {}

  // 手动运行
  run(): void {
    this.loading = true;
    this.runRequest.emit("");
  }
  // 触发自动输入改变
  emitChangeText() {
    this.changeText.emit(this.inputText);
  }
}
